package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.ShoppingCart;
import com.itheima.reggie.service.ShoppingCartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @Author: wf
 * @Desc:  购物车
 * @Date: 2022-08-23 22:04:52
 */
@RestController
@RequestMapping("/shoppingCart")
public class ShoppingCartController {

    @Autowired
    private ShoppingCartService shoppingCartService;


    @GetMapping("/list")
    public R<List<ShoppingCart>> list(){

        Long currentId = BaseContext.getCurrentId();
        LambdaQueryWrapper<ShoppingCart> lqw = new LambdaQueryWrapper<>();
        lqw.eq(ShoppingCart::getUserId, currentId);
        List<ShoppingCart> shoppingCartList = shoppingCartService.list(lqw);

        return R.success(shoppingCartList);
    }

    /**
     * 功能描述: 加入购物车
     * @return com.itheima.reggie.common.R<com.itheima.reggie.entity.ShoppingCart>
     */
    @PostMapping("/add")
    public R<String> add(@RequestBody ShoppingCart shoppingCart){

        shoppingCart.setUserId(BaseContext.getCurrentId());

        // 这里为什么不能使用公共字段自动填充，报没有updateTime属性
//        shoppingCart.setCreateTime(LocalDateTime.now());

        shoppingCartService.save(shoppingCart);

        return R.success("加入成功");
    }

    /**
     * 功能描述:  清空购物车
     * @return com.itheima.reggie.common.R<java.lang.String>
     */
    @DeleteMapping("/clean")
    public R<String> clean(){

        LambdaQueryWrapper<ShoppingCart> lqw = new LambdaQueryWrapper<>();
        lqw.eq(ShoppingCart::getUserId, BaseContext.getCurrentId());
        shoppingCartService.remove(lqw);

        return R.success("清空成功");
    }


}
